package com.yaofeng.mybatis.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yaofeng.mybatis.modules.sys.entity.Role;
import com.yaofeng.mybatis.modules.sys.entity.RoleMenu;
import com.yaofeng.mybatis.modules.sys.mapper.RoleMapper;
import com.yaofeng.mybatis.modules.sys.mapper.RoleMenuMapper;
import com.yaofeng.mybatis.modules.sys.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaofeng
 * @since 2019-09-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
   private RoleMapper  roleMapper;

    @Resource
    private RoleMenuMapper  roleMenuMapper;

    @Override
    @Transactional
    public void saveRole(Role role) {
        roleMapper.insert(role);
        // 新增角色相关菜单信息
        insertRoleMenu(role);
    }

    @Override
    @Transactional
    public void updateRole(Role role) {
        roleMapper.updateById(role);
        // 删除原先role相关的菜单信息
        deleteRoleMenu(role);
        // 新增角色相关菜单信息
        insertRoleMenu(role);

    }

    /**
     * 删除原先role相关的菜单信息
     * @param role
     */
    private void deleteRoleMenu(Role role) {
        roleMenuMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId,role.getRoleId()));
    }


    /**
     * 新增角色相关菜单信息
     * @param role
     */
    private void insertRoleMenu(Role role) {
        String [] menuIds = role.getMenuIds();
        if(menuIds!=null&&menuIds.length>0){
            Arrays.stream(menuIds).forEach(id->{
                RoleMenu  roleMenu = new RoleMenu();
                roleMenu.setMenuId(Long.valueOf(id));
                roleMenu.setRoleId(role.getRoleId());
                roleMenuMapper.insert(roleMenu);
            });
        }

    }
}
